/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.chl.sasanf.jpa.nbp;

import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.RollbackException;
import javax.validation.constraints.NotNull;

/**
 *
 * @author hansena
 */
@Entity
public class OrderItem implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}) //owner side
    @JoinColumn(name = "PRODUCT_FK")
    Product product;
    @NotNull
    private int quantity;
    
    @ManyToOne
    private PurchaseOrder po;

    

    public OrderItem() {
    }

    public OrderItem(Integer quantity) {
        this.quantity = quantity;
    }
    public PurchaseOrder getPo() {
        return po;
    }

    //CallBack
    @PrePersist
    @PreUpdate
    public void validateQuantity(){
        System.out.println("Callback checking quantity");
        if( quantity < 1 || quantity > 1000 ){
            System.out.println("Callback checking quantity");
            throw new RollbackException("Quantity must be: 1-1000");
        }

    }

    public void setPo(PurchaseOrder po) {
        this.po = po;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof OrderItem)) {
            return false;
        }
        OrderItem other = (OrderItem) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "edu.chl.sasanf.jpa.nbp.OrderItem[id=" + id + "]";
    }

}
